'use strict';
const mongoose = require('mongoose');
const AutoNubmerModel = mongoose.models['AutoNumber'];
const configData = require('./../gameUser_data');
const common = require('../../util/common');

let schema = new mongoose.Schema({
    // 玩家唯一id
    id: {
        type: Number,
        required: true,
        index: {
            unique: true
        }
    },
    openid: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    token: String,
    // 性别
    sex: Number,
    // 昵称
    nickname: String,
    // 头像
    headImgUrl: String,
    // 注册时间
    registerTimeTick:{
        type:Number,
        default:0
    },
    // 最后登录时间
    lastLoginTick: {
        type:Number,
        default:0
    },
    // 注册后登录记录
    loginTicks: {
        type: Array,
        default: [],
    },
    // 0正常账户  1测试账户  2机器人陪玩账户
    status:{
        type:Number,
        default:0
    },
    // 地址
    address: {
        type: String,
        "default": ""
    },
    // 来源appid
    referrerInfoAppId:{
        type:String,
        default : '',
    },
    // 谁邀请我过来的
    parentId : {
        type : String,
        default :'',
        index:true
    },
    // 在线时长
    onLineTime : {
        type : Number,
        default : 0
    },
    // 经度
    longitude: {
        type: Number,
        "default": 0
    },
    // 纬度
    latitude: {
        type: Number,
        "default": 0
    },
    // 点击的友情链接
    clickFLs: {
        type: Array,
        default: []
    },
    // 打开的友情链接
    openFLs: {
        type: Array,
        default: []
    },
    // 注册来源appid
    registerAppId: {
        type: String,
        default: ''
    },
    //0微信 1百度 2qq 4头条
    platform:{
        type: Number,
        default: 0
    },
    // 签到时间戳
    signTime: {
        type: Number,
        default: 0
    },
    // 累计签到次数
    signCount:{
        type:Number,
        default:0
    },
    // 金币
    goldCoin: {
        type: Number,
        default: 0
    },
    // 玩家等级
    level: {
        type: Number,
        default: 0,
    },
    // 使用皮肤
    usSkin: {
        type: Number,
        default: 0,
    },
    // 使用泡泡
    usPaopao: {
        type: Number,
        default: 0
    },
    // 所有角色皮肤*12(-1：金币购买，0：已拥有，1：视频购买)
    skinArr: {
        type: String,
        default: '0|-1|-1|-1|-1|-1|-1|-1|-1|-1|3|2'
    },
    // 所有泡泡*4
    paopaoArr: {
        type: String,
        default: '0|-1|-1|-1|-1|2|3'
    },
    // 游戏前获取的道具（泡泡|复活针|鞋子）0：未拥有
    readyProp: {
        type: String,
        default: '0|0|0',
    },
    // 连胜次数
    winCount: {
        type: Number,
        default: 0
    },
    // 是否收藏
    isCollection: {
        type: Number,
        default: 0,
    },
    // 匿名openid
    anonymous_openid: {
        type: String,
        default: '',
    },
    // 是否过了新手引导
    isGuidence: {
        type: Boolean,
        default: false,
    },
});

schema.index({id: 1}, {unique: true});
schema.index({openid: 1, token: 1}, {unique: true});
schema.index({openid: 1}, {unique: true});
schema.index({registerTimeTick: -1}, {unique: false});
schema.index({level: -1}, {unique: false});
schema.index({anonymous_openid: -1}, {unique: false});

schema.statics = {
    async weChatLogin(data) {
        let gameUser = await this.findOne({openid: data.openid});
        if(!gameUser && data.anonymous_openid){
            gameUser = await this.findOne({anonymous_openid: data.anonymous_openid});
            if(!gameUser || !data.nickname && (!gameUser.nickname || data.openid && gameUser.nickname.includes('游客'))){
                let nickname = data.openid ? '字节' : '游客';
                data.nickname = nickname + common.getRandName();
            }
        }
        data.openid = data.openid || data.anonymous_openid;
        if (!!gameUser) {
            delete data.referrerInfoAppId;
            gameUser.loginAutoRun();
            gameUser.lastLoginTick = new Date().getTime();
            Object.assign(gameUser, data);
            await gameUser.save();
        } else {
            data.lastLoginTick = Date.now();
            if(!data.nickname){
                data.nickname = data.loginType == 105 ? 'QQ' : 'WX';
                data.nickname += common.getRandName();
            }
            let id = await AutoNubmerModel.getNewNumber('GameUser');
            gameUser=await this.create(Object.assign(data, {
                id: id,
                registerTimeTick: new Date().getTime()
            }));
            // gameUser.usSkin = gameUser.sex == 1 ? 0 : 1; //新用户确认角色
            gameUser.loginAutoRun();
            //如果是用户推广来的用户，则发放奖励
            if(!!data.referrerInfoAppId){
                gameUser.referrerInfoAppId = data.referrerInfoAppId;
                gameUser.registerAppId = data.referrerInfoAppId;
            }
            await gameUser.save();
        }
        return gameUser;
    },
    async list(params={rows:20,page:1}) {
        let rows = parseInt(params.rows);
        let page = parseInt(params.page);
        if (page == 0) {
            page = 1;
        }
        let skipCnt = (page - 1) * rows;
        let total = await this.find({}).countDocuments();
        let data = await this.find({}).sort({_id: -1}).limit(rows).skip(skipCnt);
        return {total: total, gameUsers: data};
    },
    async getOne(obj){
        let gameUser = await this.findOne(obj);
        if(!gameUser){
            throw new Error('用户不存在')
        }
        return gameUser
    }
};

schema.methods = {
    rankingList: require('./gameUser.rankingList'),
    friendlyLink: require('./gameUser.friendlyLink'),
    friendlyLinkClick: require('./gameUser.friendlyLinkClick'),
    channelEvent: require('./gameUser.channelEvent'),
    chatMessage: require('./gameUser.chatMessage'),
    //获取用户信息
    getMessage(options) {
        return {
            _id: this._id.toString(),
            openid: this.openid,
            id: this.id,
            sex: this.sex,
            nickname: this.nickname,
            headImgUrl: this.headImgUrl,
            token:this.token,
            address: this.address,
            level:this.level,
            registerAppId: this.registerAppId,
            registerTimeTick : this.registerTimeTick,
            levelName: this.getLevelName({self: this}),
            usSkin: this.usSkin,
            usPaopao: this.usPaopao,
            skinArr: this.skinArr,
            paopaoArr: this.paopaoArr,
            readyProp: this.readyProp,
            goldCoin: this.goldCoin,
            winCount: this.winCount,
            signCount: this.signCount,
            signTime: this.signTime,
            isCollection: this.isCollection,
            isGuidence: this.isGuidence,
            sceneNum: 3003,
        };
    },
    async checkLogin(options){
        this.loginAutoRun();
        this.lastLoginTick = new Date().getTime();
        let msg = this.getMessage();
        return Object.assign(msg,{
            adTimeOut: 60000,
            levelDescriptions: configData.levelDescriptions,
            friendlyLinks: await this.friendlyLink.list(options),
            rankList: this.rankingList.getRankList(0),
            // messages: await this.chat.newTest({self: options.self, channel:'world'})
        });
    },
    // 登陆自动运行
    loginAutoRun(){
        let now = new Date();
        let upDate = new Date(this.lastLoginTick);
        if(upDate.toLocaleDateString() !== now.toLocaleDateString()){
            this._lastDayLoginTicks();
        }
        if((Date.now() - upDate.getTime()) > 30 * 24 * 60 * 60 * 1000 ){
            this.dropLevel();
        }
    },
    // 计算近30天的留存情况
    _lastDayLoginTicks(){
        let dt = this.lastLoginTick - this.registerTimeTick;
        let day = Math.floor(dt/(24*60*60*1000));
        console.log('day =', day);
        if(day >=0 && day < 30){
            return this.loginTicks.push(this.lastLoginTick);
        }
    },
    // 一个月前登陆掉4个段位
    dropLevel(){
        let index = this.getLevelIndex();
        let des = configData.levelDescriptions;
        let nowIndex = index > 4 ? index - 4 : 0;
        this.level = des[nowIndex].min;
    },
    // 加分
    levelUp(level){
        this.level += level;
    },
    // 掉分
    levelDown(level){
        this.level = this.level > level ? (this.level - level) : 0;
    },
    // 获取段位下标
    getLevelIndex(){
        return configData.levelDescriptions.findIndex(
            item => (this.level >= item.min && this.level < item.max)
        );
    },
    // 获取段位名称
    getLevelName(){
        let index = this.getLevelIndex();
        let levelObj = configData.levelDescriptions[index];
        return levelObj ? levelObj.levelName : '未知等级';
    },
    //增加一个属性数量
    async attrAdd(options={propName:'goldCoin',count:'1'}){
        options.count=parseInt(options.count);
        this[options.propName]+=options.count;
    },
    // 改变属性值
    async attrString(options={propName:'lotteryData',value:'1'}){
        this[options.propName]=options.value;
    },
    // 改变多个属性值
    async attrArr(options={propArr,valueArr}){
        for(let i=0 ; i < options.propArr.length ; i++){
            this[options.propArr[i]] = options.valueArr[i];
        }
    },
    // 获取服务器
    async getRandomServer(options){
        let DockerModel = mongoose.models['Docker'];
        let type = 0;
        if(!!options.type) type = parseInt(options.type);
        let dockers = await DockerModel.find({type: type, v: options.v});
        if(dockers.length <= 0){
            throw new Error('当前没有服务器在线');
        }
        let randomIndex = Math.floor(Math.random() * dockers.length);
        return dockers[randomIndex].getMessage();
    },
};

module.exports = schema;